import {setToken, setRefreshToken, removeToken, removeRefreshToken} from '@/util/auth'
import {Message} from 'element-ui'
import {setStore, getStore} from '@/util/store'
import {isURL, validatenull} from '@/util/validate'
import {deepClone} from '@/util/util'
import website from '@/config/website'
import {
  loginByUsername,
  getUserInfo,
  logout,
  refreshToken,
  getButtons,
  getForum,
  getMyForum,
  getHotForum,
  getHotColumn,
  getColumnTheme,
  getPostedList,
  getMyDate,
  getMyReply,
  getRemove,
  getSave,
  getTree,
  getTheemeView,
  getSaveReply,
  getSaveFabulousNumber,
  getMyTheme,
  getCreateRemove,
  getRemoveFabulousNumber,
  getComponents
} from '@/api/user'
import {getTopMenu, getRoutes, getWebRouter, getWebRouters} from '@/api/system/menu'
import {getUserInfoSso} from '@/api/system/user'

function addPath(ele, first) {
  const menu = website.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || 'name',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  if (!isChild) ele[propsDefault.children] = [];
  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children].forEach(child => {
      addPath(child);
    })
  }

}

let roleIds = ['1490859421955674114']

function isArray (id, arr) {
  let bool = 0
  if (arr.length) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === id) {
        bool = 1
        break
      }
    }
  }
  return bool
}

function restructureMenu (list, roleId) {
  let listArr = []
  let notId = ['1490905165769187329','1490905325106601985']
  console.log('当前角色ID', roleId)
  console.log('所有菜单', list)
  if (isArray(roleId, roleIds)) {
    for (let i = 0; i < list.length; i++) {
      let list1 = list[i]
      if (list1.children && list1.children.length) {
        let listArr1 = []
        for (let j = 0; j < list1.children.length; j++) {
          let list2 = list1.children[j]
          if (isArray(list2.id, notId)) {
            if (list2.children.length) {
              for (let k of list2.children) {
                listArr1.push(k)
              }
            }
          } else {
            listArr1.push(list2)
          }
        }
        if (listArr1.length) {
          list1.children = listArr1
          listArr.push(list1)
        }
      } else {
        listArr.push(list1)
      }
    }
  } else {
    listArr = list
  }
  console.log(listArr)
  return listArr

}

const user = {
  state: {
    tenantId: getStore({name: 'tenantId'}) || '',
    userInfo: getStore({name: 'userInfo'}) || [],
    permission: getStore({name: 'permission'}) || {},
    comonents: getStore({name: 'comonents'}) || {},
    roles: [],
    menu: getStore({name: 'menu'}) || [],
    menuId: getStore({name: 'menuId'}) || [],
    menuAll: getStore({name: 'menuAll'}) || [],
    topMenu: getStore({name: 'topMenu'}) || [],
    leftMenu: getStore({name: 'leftMenu'}) || [],
    token: getStore({name: 'token'}) || '',
    refreshToken: getStore({name: 'refreshToken'}) || '',
  },
  actions: {
    //根据用户名登录
    LoginByUsername({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo.tenantId, userInfo.username, userInfo.password, userInfo.type, userInfo.key, userInfo.code).then(res => {
          const data = res.data;
          if (data.error_description) {
            Message({
              message: data.error_description,
              type: 'error'
            })
          } else {
            commit('SET_TOKEN', data.access_token);
            commit('SET_REFRESH_TOKEN', data.refresh_token);
            commit('SET_TENANT_ID', data.tenant_id);
            commit('SET_USER_INFO', data);
            commit('DEL_ALL_TAG');
            commit('CLEAR_LOCK');
          }
          resolve();
        }).catch(error => {
          reject(error);
        })
      })
    },
    //根据用户名登录
    LoginBySSO({commit, dispatch}, token) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', token);
        // commit('SET_REFRESH_TOKEN', data.refresh_token);
        commit('SET_TENANT_ID', '000000');
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        getRoutes().then((res) => {
          const data = res.data.data
          let role_id = this.getters.userInfo.role_id
          let menu1 = restructureMenu(data, role_id)
          let menu = deepClone(menu1)
          menu.forEach(ele => {
            addPath(ele, true);
          });
          commit('SET_MENUAll', menu)
          dispatch('GetButtons');
          dispatch('getComponents');
          getUserInfoSso().then((res) => {
            const data = res.data.data
            commit('SET_USER_INFO', data);
            // resolve()
          }).catch(err => {
            // reject(err)
          })
          resolve(menu)
        })

      }).catch(error => {
        reject(error);
      })
    },
    GetButtons({commit}) {
      return new Promise((resolve) => {
        getButtons().then(res => {
          const data = res.data.data;
          commit('SET_PERMISSION', data);
          resolve();
        })
      })
    },
    getComponents({commit}) {
      return new Promise((resolve) => {
        getComponents().then(res => {
          const data = res.data.data;
          console.log(data,'getComponents')
          commit('SET_COMPONENTS', data);
          resolve();
        })
      })
    },
    //根据手机号登录
    LoginByPhone({commit}, userInfo) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.phone, userInfo.code).then(res => {
          const data = res.data.data;
          commit('SET_TOKEN', data);
          commit('DEL_ALL_TAG');
          commit('CLEAR_LOCK');
          resolve();
        })
      })
    },
    GetUserInfo({commit}) {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          const data = res.data.data;
          commit('SET_ROLES', data.roles);
          resolve(data);
        }).catch(err => {
          reject(err);
        })
      })
    },
    //刷新token
    refreshToken({state, commit}) {
      // console.log('handle refresh token')
      // return new Promise((resolve, reject) => {
      //   refreshToken(state.refreshToken, state.tenantId).then(res => {
      //     const data = res.data;
      //     commit('SET_TOKEN', data.access_token);
      //     commit('SET_REFRESH_TOKEN', data.refresh_token);
      //     resolve();
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },
    // 登出
    LogOut({commit}) {
      return new Promise((resolve, reject) => {
        // logout().then(() => {
        //     commit('SET_TOKEN', '');
        //     commit('SET_MENU', []);
        //     commit('SET_MENU_ID', {});
        //     commit('SET_MENU_ALL', []);
        //     commit('SET_ROLES', []);
        //     commit('DEL_ALL_TAG');
        //     commit('CLEAR_LOCK');
        //     removeToken();
        //     removeRefreshToken();
        //     resolve();
        // }).catch(error => {
        //     reject(error)
        // })
        resolve();
      })
    },
    //注销session
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_MENU_ID', {});
        commit('SET_MENU_ALL', []);
        commit('SET_MENU', []);
        commit('SET_ROLES', []);
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        localStorage.removeItem('password');
        removeToken();
        removeRefreshToken();
        resolve();
      })
    },
    //获取顶部菜单
    GetTopMenu({commit}) {
      return new Promise(resolve => {
        getWebRouter().then((res) => {
          const data = res.data.data || [];
          commit('SET_TOP_MENU', data);
          resolve(data)
        })
        // 获取左侧菜单
        getWebRouters().then((res) => {
          const data = res.data.data || [];
          commit('SET_LEFT_MENU', data);
          // resolve(data)
        })
      })
    },
    GetTopMenuFirstLocal({commit}, topMenuId) {
      return new Promise(resolve => {
        let returndata = []
        let leftMenu = getStore({name: 'leftMenu'}) || [];
        if (leftMenu.length > 0) {
          leftMenu.forEach(x => {
            if (x.id === topMenuId) {
              returndata.push(x);
            }else{
              returndata.push(x);
            }
          })
          let role_id = this.getters.userInfo.role_id
          let menu1 = restructureMenu(returndata[0].children[0].children, role_id)
          let menu = deepClone(menu1)
          menu.forEach(ele => {
            addPath(ele, false);
          });
          commit('SET_MENU', menu)
          resolve(returndata)
        } else {
          getWebRouters().then((res) => {
            const data = res.data.data || [];
            commit('SET_TOP_MENU', data);
            data.forEach(x => {
              if (x.id === topMenuId) {
                returndata.push(x);
              }else{
                returndata.push(x);
              }
            })
            let role_id = this.getters.userInfo.role_id
            let menu1 = restructureMenu(returndata[0].children[0].children, role_id)
            let menu = deepClone(menu1);
            // console.log(data, "menu")
            menu.forEach(ele => {
              addPath(ele, false);
            });
            commit('SET_MENU', menu)
            resolve(returndata)
          })
        }
      })
    },
    //获取系统菜单
    GetMenu({commit, dispatch}, topMenuId) {
      return new Promise(resolve => {
        getRoutes(topMenuId).then((res) => {
          const data = res.data.data
          let role_id = this.getters.userInfo.role_id
          let menu1 = restructureMenu(data, role_id)
          let menu = deepClone(menu1)
          menu.forEach(ele => {
            addPath(ele, true);
          });
          commit('SET_MENU', menu)
          dispatch('GetButtons');
          resolve(menu);
        })
      })
    },
    //获取系统菜单   获取全部菜单
    GetMenuAll({commit, dispatch}) {
      return new Promise(resolve => {
        getRoutes().then((res) => {
          const data = res.data.data
          let role_id = this.getters.userInfo.role_id
          let menu1 = restructureMenu(data, role_id)
          let menu = deepClone(menu1)
          menu.forEach(ele => {
            addPath(ele, true);
          });
          commit('SET_MENUAll', menu)
          dispatch('GetButtons');
          resolve(menu)
        })
      })
    },
    // 获取论坛主题列表
    GetForum({}, forumId) {
      return new Promise(resolve => {
        getForum(forumId).then((res) => {
          const data = res.data.data
          let ThemeLists = data;
          resolve(ThemeLists)
        })
      })
    },
    // 获取 我创建的论坛主题列表
    GetMyForum({}, forumId) {
      return new Promise(resolve => {
        getMyForum(forumId).then((res) => {
          const data = res.data.data
          let myThemeLists = data;
          resolve(myThemeLists)
        })
      })
    },
    // 热门主题列表
    GetHotForum() {
      return new Promise(resolve => {
        getHotForum().then((res) => {
          const data = res.data.data
          let role_id = this.getters.userInfo.role_id
          let HotThemeLists1 = restructureMenu(data, role_id)
          let HotThemeLists = deepClone(HotThemeLists1)
          HotThemeLists.forEach(ele => {
            addPath(ele, true);
          });
          resolve(HotThemeLists)
        })
      })
    },
    // 热门版块列表
    GetHotColumn() {
      return new Promise(resolve => {
        getHotColumn().then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetColumnTheme() {
      return new Promise(resolve => {
        getColumnTheme().then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    // 论坛发帖榜
    GetPostedList() {
      return new Promise(resolve => {
        getPostedList().then((res) => {
          const data = res.data;
          resolve(data);
        })
      })
    },
    // getMyDate
    GetMyDate() {
      return new Promise(resolve => {
        getMyDate().then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    // getMyReply
    GetMyReply({}, currentPage) {
      return new Promise(resolve => {
        getMyReply(currentPage).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    // 删除回复
    GetRemove({}, id) {
      return new Promise(resolve => {
        getRemove(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    // 发布 创建主题
    GetSave({}, params) {
      return new Promise(resolve => {
        getSave(params).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetTree() {
      return new Promise(resolve => {
        getTree().then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetTheemeView({}, id) {
      return new Promise(resolve => {
        getTheemeView(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetSaveReply({}, id) {
      return new Promise(resolve => {
        getSaveReply(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetSaveFabulousNumber({}, id) {
      return new Promise(resolve => {
        getSaveFabulousNumber(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetRemoveFabulousNumber({}, id) {
      return new Promise(resolve => {
        getRemoveFabulousNumber(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetMyTheme({}, id) {
      return new Promise(resolve => {
        getMyTheme(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
    GetCreateRemove({}, id) {
      return new Promise(resolve => {
        getCreateRemove(id).then((res) => {
          const data = res.data.data;
          resolve(data);
        })
      })
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      setToken(token);
      state.token = token;
      setStore({name: 'token', content: state.token, type: 'session'})
    },
    SET_MENU_ID(state, menuId) {
      state.menuId = menuId;
      setStore({name: 'menuId', content: state.menuId, type: 'session'})
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll
      setStore({name: 'menuAll', content: state.menuAll, type: 'session'})
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      setRefreshToken(refreshToken)
      state.refreshToken = refreshToken;
      setStore({name: 'refreshToken', content: state.refreshToken, type: 'session'})
    },
    SET_TENANT_ID: (state, tenantId) => {
      state.tenantId = tenantId;
      setStore({name: 'tenantId', content: state.tenantId, type: 'session'})
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({name: 'userInfo', content: state.userInfo})
    },
    SET_MENU: (state, menu) => {
      state.menu = menu;
      // if (!validatenull(menu)) {
      //   const obj = menuAll.filter(ele => ele.path === menu[0].path)[0];
      //   if (!obj) {
      //     menuAll = menuAll.concat(menu);
      //     state.menuAll = menuAll
      //   }
      //   setStore({name: 'menuAll', content: menuAll, type: 'session'})
      // }
      setStore({name: 'menu', content: state.menu, type: 'session'})
    },
    SET_TOP_MENU: (state, topmenu) => {
      state.topmenu = topmenu;
      // if (!validatenull(menu)) {
      //   const obj = menuAll.filter(ele => ele.path === menu[0].path)[0];
      //   if (!obj) {
      //     menuAll = menuAll.concat(menu);
      //     state.menuAll = menuAll
      //   }
      //   setStore({name: 'menuAll', content: menuAll, type: 'session'})
      // }
      setStore({name: 'topMenu', content: state.topmenu, type: 'session'})
    },
    // 获取左侧菜单
    SET_LEFT_MENU: (state, leftmenu) => {
      state.leftmenu = leftmenu;
      setStore({name: 'leftmenu', content: state.leftmenu, type: 'session'})
      setStore({name: 'leftmenu', content: state.leftmenu})
    },
    //  获取全部菜单
    SET_MENUAll: (state, menu) => {
      let menuAll = menu;
      state.menuAll = menu;
      // if (!validatenull(menu)) {
      //   const obj = menuAll.filter(ele => ele.path === menu[0].path)[0];
      //   if (!obj) {
      //     menuAll = menuAll.concat(menu);
      //     state.menuAll = menuAll
      //   }
      //   setStore({name: 'menuAll', content: menuAll, type: 'session'})
      // }
      setStore({name: 'menuAll', content: menuAll, type: 'session'})
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      let result = [];

      function getCode(list) {
        list.forEach(ele => {
          if (typeof (ele) === 'object') {
            const chiildren = ele.children;
            const code = ele.code;
            if (chiildren) {
              getCode(chiildren)
            } else {
              result.push(code);
            }
          }
        })
      }

      getCode(permission);
      state.permission = {};
      result.forEach(ele => {
        state.permission[ele] = true;
      });
      setStore({name: 'permission', content: state.permission, type: 'session'})
    },
    SET_COMPONENTS: (state, comonents) => {
      let result = [];

      function getCode(list) {
        list.forEach(ele => {
          if (typeof (ele) === 'object') {
            const chiildren = ele.children;
            const code = ele.code;
            if (chiildren) {
              getCode(chiildren)
            } else {
              result.push(code);
            }
          }
        })
      }

      getCode(comonents);
      state.comonents = {};
      result.forEach(ele => {
        state.comonents[ele] = true;
      });
      setStore({name: 'comonents', content: state.comonents, type: 'session'})
    }
  },



}
export default user
